package dev.mcdd.security.handler;


import dev.mcdd.common.helper.HttpHelper;
import dev.mcdd.common.json.JsonHelper;
import dev.mcdd.security.adapter.SecurityUserDetailsAdapter;
import dev.mcdd.user.domain.UserMapstruct;
import dev.mcdd.user.domain.response.UserInfo;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author mcdd1024
 * @name LoginAuthenticationHandler
 * @since 2025/1/16 08:19
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LoginAuthenticationHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler {

    private final UserMapstruct mapstruct;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        try (PrintWriter writer = HttpHelper.responseWriterCustomer(response)) {
            SecurityUserDetailsAdapter adapter = (SecurityUserDetailsAdapter) authentication.getPrincipal();
            UserInfo userInfo = mapstruct.toUserInfo(adapter.user());
            writer.write(JsonHelper.toJSON(userInfo));
        }
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        try (PrintWriter writer = HttpHelper.responseWriterCustomer(response)) {
            writer.write("login failed");
        }
    }

}
